package com.xinrui.sunnyday.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.xinrui.sunnyday.dao.OrdersettingDao;
import com.xinrui.sunnyday.exception.SunnydayException;
import com.xinrui.sunnyday.pojo.OrderSetting;
import com.xinrui.sunnyday.service.OrdersettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Transactional
@Service(interfaceClass = OrdersettingService.class)
public class OrdersettingServiceImpl implements OrdersettingService {

    @Autowired
    private OrdersettingDao ordersettingDao;

    @Override
    public void add(List<OrderSetting> orderSettings) throws SunnydayException {
        for (OrderSetting orderSetting : orderSettings) {
//            获取数据库中该日期的数据
            OrderSetting orderSettingDB = ordersettingDao.findByOrderDate(orderSetting.getOrderDate());
//            判断数据库中是否存在该日期的订单设置
            if (null != orderSettingDB) {//存在
//                判断该日期已预约人数是否大于可预约人数
                if (orderSettingDB.getReservations() > orderSetting.getNumber()) {//大于
//                    抛出异常 返回错误信息
                    throw new SunnydayException(orderSetting.getOrderDate() + ": 该日期已预约人数大于可预约人数!");
                } else {//不大于
//                    根据日期修改数据
                    ordersettingDao.updateByOrderDate(orderSetting);
                }
            } else {//不存在
//                直接添加
                ordersettingDao.add(orderSetting);
            }
        }
    }

    @Override
    public List<Map<String, Integer>> findDataByMonth(String month) {
        month = month + "-01";
        return ordersettingDao.findDataByMonth(month);
    }

    @Override
    public void update(OrderSetting orderSetting) throws SunnydayException {
//        获取数据库中该日期的数据
        OrderSetting orderSettingDB = ordersettingDao.findByOrderDate(orderSetting.getOrderDate());
//            判断数据库中是否存在该日期的订单设置
        if (null != orderSettingDB) {//存在
//                判断该日期已预约人数是否大于可预约人数
            if (orderSettingDB.getReservations() > orderSetting.getNumber()) {//大于
//                    抛出异常 返回错误信息
                throw new SunnydayException(orderSetting.getOrderDate() + ": 该日期已预约人数大于可预约人数!");
            } else {//不大于
//                    根据日期修改数据
                ordersettingDao.updateByOrderDate(orderSetting);
            }
        } else {//不存在
//                直接添加
            ordersettingDao.add(orderSetting);
        }
    }

}
